package us.mooresr.aircraftscheduling.server.handler;

import us.mooresr.aircraftscheduling.server.DAO;
import us.mooresr.aircraftscheduling.shared.action.DeleteUserAction;
import us.mooresr.aircraftscheduling.shared.action.DeleteUserResult;
import us.mooresr.aircraftscheduling.shared.model.Reservation;
import us.mooresr.aircraftscheduling.shared.model.User;
import us.mooresr.aircraftscheduling.shared.model.UserDetail;

import com.googlecode.objectify.Key;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;

public class DeleteUserHandler 
	implements ActionHandler<DeleteUserAction, DeleteUserResult> {

	@Override
	public DeleteUserResult execute(DeleteUserAction action,
			ExecutionContext context) throws ActionException {
		DAO dao = new DAO();
		
		dao.ofy().delete(User.class, action.getUser().getUserId());
		dao.ofy().delete(UserDetail.class, action.getUser().getUserId());
		
		// Delete reservationsfor this user
		Iterable<Key<Reservation>> allKeys = dao.ofy().query(Reservation.class).filter("reservingUserId", action.getUser().getUserId()).fetchKeys();
		dao.ofy().delete(allKeys);
		
		return new DeleteUserResult(action.getUser());
	}

	@Override
	public Class<DeleteUserAction> getActionType() {
		return DeleteUserAction.class;
	}

	@Override
	public void undo(DeleteUserAction action, DeleteUserResult result,
			ExecutionContext context) throws ActionException {
		
		
	}

}
